﻿using Coldairarrow.Entity.Goods;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.DbHelpers;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Goods
{
    public class BTB_ShippingAddressBusiness : BaseBusiness<BTB_ShippingAddress>, IBTB_ShippingAddressBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public BTB_ShippingAddressBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<BTB_ShippingAddress>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var result = GetIQueryable().Where(z => z.Userid == _operator.UserId);
            var where = LinqHelper.True<BTB_ShippingAddress>();
            int count = result.Count();
            var q = await result.Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows)
                .ToListAsync();

            return new PageResult<BTB_ShippingAddress> { Data = q, Total = count };
        }

        public async Task<BTB_ShippingAddress> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }
        public async Task AddDataAsync(BTB_ShippingAddress data)
        {
            if (data.DefalutAddress == true)
            {
                var aa = GetIQueryable().Where(q => q.Userid == _operator.UserId && q.DefalutAddress == true).ToList();
                if (aa.Count() > 0)
                {
                    var sql = "UPDATE [BTB_ShippingAddress] SET [DefalutAddress] = 0 WHERE Userid = '" + _operator.UserId + "' ";
                    DbHelperSQL.ExecuteSql(sql);
                }
            }
            BTB_ShippingAddress data1 = new BTB_ShippingAddress()
            {
                id = GuidHelper.GenerateKey(),
                Userid = _operator.UserId,
                CreatorId = data.CreatorId,
                Phone = data.Phone,
                Address = data.Address,
                DetailedAddress = data.DetailedAddress,
                Email = data.Email,
                Title = data.Title,
                CreateTime = data.CreateTime,
                Editor = data.Editor,
                EditTime = data.EditTime,
                Deleted = data.Deleted,
                DefalutAddress = data.DefalutAddress
            };
            await InsertAsync(data1);
        }

        public async Task UpdateTheDataAsync(BTB_ShippingAddress data)
        {
            var model = await GetEntityAsync(data.id);
            if (!model.Userid.Equals(_operator.UserId))
            {
                throw new BusException("无法修改非本人地址", errorCode: -1);
            }

            //接收修改值
            model.DefalutAddress = data.DefalutAddress;
            model.Phone = data.Phone;
            model.Address = data.Address;
            model.DetailedAddress = data.DetailedAddress;
            model.Email = data.Email;
            model.Title = data.Title;
            model.Userid = _operator.UserId;
            model.CreatorId = data.CreatorId;

            if (model.DefalutAddress == true)
            {
                var count1 = GetIQueryable().Where(a => a.Userid == _operator.UserId).Count();
                var sql = "UPDATE BTB_ShippingAddress SET DefalutAddress = 0 WHERE Userid = '" + _operator.UserId + "' ";
                var count = DbHelperSQL.ExecuteSql(sql);
                if (count == count1)
                {
                    await UpdateAsync(model);
                }
                else
                {
                    throw new BusException("请联系管理员", errorCode: -1);
                }
            }
            else
            {
                await UpdateAsync(model);
            }
        }


        /// <summary>
        /// 修改默认地址
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task SetDefaultAdress(string id)
        {
            var n = await UpdateAsync(a => !a.id.Equals(id) && a.Userid.Equals(_operator.UserId), c => c.DefalutAddress = false);

            var k = await UpdateAsync(a => a.id.Equals(id) && a.Userid.Equals(_operator.UserId), c => c.DefalutAddress = true);

            if (k == 0)
            {
                throw new BusException("未查询到此记录,修改默认地址失败", errorCode: -1);
            }

            #region
            //var sList = GetIQueryable().Where(a => a.Userid == _operator.UserId).ToList();
            //var model = sList.Where(x => x.id.Equals(id)).FirstOrDefault();
            //if (model.IsNullOrEmpty())
            //{
            //    throw new BusException("未查询到此记录,修改默认地址失败", errorCode: -1);
            //}
            //else
            //{
            //    int index = sList.IndexOf(model);
            //    foreach (var item in sList)
            //    {
            //        if (item.id.Equals(id))
            //        {
            //            item.DefalutAddress = true;
            //        }
            //        else
            //        {
            //            item.DefalutAddress = false;
            //        }
            //    }
            //    await UpdateAsync(sList);
            //}
            #endregion
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}